package app.itgungnir.compose.wan.business.my_collection

import androidx.lifecycle.ViewModel
import app.itgungnir.compose.wan.utils.*
import com.google.gson.JsonElement
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

class MyCollectionViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val dialogLoadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    val dialogErrorState = MutableSharedFlow<Throwable?>()
    var loadingJob: Job? = null
    var dialogLoadingJob: Job? = null

    val dismissDialogState = MutableStateFlow<Boolean>(false)

    val myCollectionFlow = pagingSourceWithCache(
        firstPageIndex = 0,
        pageSize = 20,
        networkRequest = { wanAndroidService.getMyCollections(it).wanResponse<WanPagingResponse<MyCollection>>() },
        queryCache = { dao -> dao.queryMyCollections() },
        clearCache = { dao -> dao.deleteAllMyCollections() },
        appendCache = { list, dao -> dao.insertAllMyCollections(list) }
    )

    fun addCollection(title: String, link: String, author: String) = launch(dialogLoadingState, dialogErrorState) {
        dismissDialogState.emit(false)
        if (title.isEmpty()) {
            throw IllegalArgumentException("标题不能为空")
        }
        if (link.isEmpty()) {
            throw IllegalArgumentException("链接不能为空")
        }
        val response = wanAndroidService.addCollection(title, link, author).wanResponse<MyCollection>()
        response?.takeIf { it.id > 0 }?.let {
            WanDatabase.dao.insertMyCollection(it)
        }
        dismissDialogState.emit(true)
    }.also { dialogLoadingJob = it }

    fun updateCollection(collection: MyCollection) = launch(dialogLoadingState, dialogErrorState) {
        dismissDialogState.emit(false)
        if (collection.title.isNullOrEmpty()) {
            throw IllegalArgumentException("标题不能为空")
        }
        if (collection.link.isNullOrEmpty()) {
            throw IllegalArgumentException("链接不能为空")
        }
        wanAndroidService.updateCollection(
            collection.id,
            collection.title ?: "",
            collection.link ?: "",
            collection.author ?: ""
        ).wanResponse<JsonElement>()
        WanDatabase.dao.updateMyCollection(collection)
        dismissDialogState.emit(true)
    }.also { dialogLoadingJob = it }

    fun deleteCollection(collection: MyCollection) = launch(loadingState, errorState) {
        val collectionId = collection.id
        val collectionOriginId = collection.originId
        wanAndroidService.deleteCollection(collectionId, collectionOriginId).wanResponse<JsonElement>()
        WanDatabase.dao.deleteMyCollection(collectionId)
        WanDatabase.dao.updateHomeArticleCollect(collectionOriginId, false)
    }.also { loadingJob = it }
}
